﻿<!DOCTYPE html>
<html>
<head>
    <title>CGI</title>
</head>
<body>
    <h1>Our Page</h1>
    <script>
        //01
        //the function is called beacause of () (double parenthesis)

        (function () {
            console.log('Executed!');
        })();

        //or

        (function () {
            console.log('Executed!');
        }());


        //02
        //we have an IIFE and it's has it's own variable "employeeName"
        //the variable "employeeName" is in scope of the function beacuse of var, it's not in global scope
        /*
        (function () {
            var employeeName = 'Jill';
        })();
        //here employeeName is in global scope,hence error
        //this is how IIFE prevent to polute the global scope
        console.log(employeeName);
        */

        //03
        //very common pattern
        //every sigle app/library have single variable, jquery has jquery variable, angular has angular variable
        //an application has a variable in global namespace has "app" or name of the app
        //below app (empty) object passed to the IIFE function and we rename this to "ns" for namespace
        /*
        var app = {};
        (function (ns) {
            ns.name = 'CGI';
        })(app);

        console.log(app.name);
        */

        //04
        //to load out jquery
        //"$" pass here in IIFE, which guranteed  that $ sign is equal to jQuery
        /*
        var app = {}
        var jQuery = {};
        (function (ns, $) {
            ns.name = 'CGI';
            console.log($ === jQuery);
        })(app, jQuery);
        */

        //05
        //to set undefined
        /*
        var app = {};
        var jQuery = {};
        (function (ns, $, undefined) {
            ns.name = 'CGI';
            console.log(undefined);
        })(app, jQuery);
        */

        //06
        //another way to create IIFE
        //by using unary (+) operator
        /*
        +function () {
            var employeeName = 'Jill';
            console.log('Executed!');
        }();
        console.log(employeeName);
        */
    </script>
</body>
</html>